package com.kjc.demo.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author kuaiting
 * WebSocket
 */

public class WebSocketServer {


    public void start() {
        // 一个主线程组
        NioEventLoopGroup mainGroup = new NioEventLoopGroup();
        //一个工作线程组
        NioEventLoopGroup subGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(mainGroup, subGroup)
                    //设置队列大小
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .channel(NioServerSocketChannel.class)
                    // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //添加自定义初始化处理器
                    .childHandler(new WSServerInitialzer());
            ChannelFuture channelFuture = serverBootstrap.bind(8082).sync();
            channelFuture.channel().closeFuture().sync();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭主线程组
            mainGroup.shutdownGracefully();
            //关闭工作线程组
            subGroup.shutdownGracefully();
        }


    }
}

